﻿using MediatR;
using Process.Api.Application.Command.BOM;
using Process.BLL;
using Process.ErrorCod;
using Process.Infastructure;
using Process.Model;

namespace Process.Api.Application.Handler.BOM
{
    public class GetGoodsinfoListHandler : IRequestHandler<GetGoodsinfoListCommand, ApiPageing<Goodsinfo>>
    {
        private readonly IProcessRepository<Goodsinfo> goodsinfoRepo;

        public GetGoodsinfoListHandler(IProcessRepository<Goodsinfo> goodsinfoRepo)
        {
            this.goodsinfoRepo = goodsinfoRepo;
        }
        /// <summary>
        /// 查询物品列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiPageing<Goodsinfo>> Handle(GetGoodsinfoListCommand request, CancellationToken cancellationToken)
        {
           var result = new ApiPageing<Goodsinfo>();
            var list =  goodsinfoRepo.GetAllAsync().Where(x => x.IsDelete == false);

            if (!string.IsNullOrEmpty(request.GoodsCode))
            {
                list = list.Where(x => x.GoodsCode != null && x.GoodsCode.Contains(request.GoodsCode));
            }
            if (!string.IsNullOrEmpty(request.GoodsName))
            {
                list = list.Where(x => x.GoodsName != null && x.GoodsName.Contains(request.GoodsName));
            }


            var query = list.OrderByDescending(x => x.Id)
                           .Skip((request.PageIndex - 1) * request.PageSize)
                           .Take(request.PageSize)
                           .ToList();
            var total = query.Count();

            result.TotalCount = total;
            result.TotalPage = (int)Math.Ceiling((double)total / request.PageSize);
            result.Code = ErrorStatus.Success;
            result.PageData = query;
            result.Message = "获取物品分页数据成功";
            return result;

        }
    }
}
